<template>
  <div>
    <el-header>
      <el-menu default-active="1"
               class="el-menu-demo"
               mode="horizontal"
               background-color="#545c64"
               text-color="#fff"
               active-text-color="#ffd04b">
        <el-menu-item index="1">处理中心</el-menu-item>
        <el-submenu index="8"
                    style="float:right">
          <template slot="title">
            <el-link v-show="Number(user.id)"
                     type="info"
                     style="margin-right:10px">欢迎您，{{ user.nickName }}</el-link>
            <el-badge :is-dot="hasToDo"
                      class="item">
              <el-avatar icon="el-icon-user-solid"></el-avatar>
            </el-badge>
          </template>
          <el-menu-item v-show="Number(user.id) && !isAdmin"
                        index="8-4"
                        @click="showMyUserInfo">个人信息</el-menu-item>
          <el-menu-item v-show="Number(user.id)"
                        index="8-5"
                        @click="isShowChangePwd = true">修改密码</el-menu-item>
          <el-menu-item v-show="Number(user.id)"
                        index="8-6"
                        @click="showApprovalDialog">
            <el-badge v-if="hasToDo"
                      :value="toDoList.length">我的待办</el-badge>
            <span v-else>我的待办</span>
          </el-menu-item>
          <el-menu-item v-show="Number(user.id)"
                        index="8-7"
                        @click="logout">注销</el-menu-item>
        </el-submenu>
      </el-menu>
    </el-header>
    <el-container>
      <el-tabs v-model="activeName"
               @tab-click="selectedTab"
               type="border-card"
               tab-position="left"
               style="height: 700px;margin-top:20px;margin-left:20px">
        <el-tab-pane name="查看课题"
                     :label="isAdmin ? '课题管理' : '查看课题'"
                     style="width:1400px">
          <template>
            <el-form inline>
              <el-form-item label="课题名称"
                            label-width="80px">
                <el-input v-model="searchExperimentForm.exName" />
              </el-form-item>
              <el-form-item label="课题描述"
                            label-width="80px">
                <el-input v-model="searchExperimentForm.exDescription" />
              </el-form-item>
              <el-form-item label="课题类别"
                            label-width="80px">
                <el-select v-model="searchExperimentForm.tyId"
                           clearable
                           placeholder="请选择">
                  <el-option v-for="item in exTypes"
                             :key="item.id"
                             :label="item.typeName"
                             :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary"
                           @click="searchExperiment">搜索</el-button>
              </el-form-item>
            </el-form>
            <el-row>
              <el-col>
                <div v-if="isAdmin"
                     style="text-align:left;margin-bottom:10px">
                  <el-button type="success"
                             size="small"
                             @click="experiments.push({})">新增</el-button>
                  <el-button type="warning"
                             size="small"
                             @click="saveExperiments">保存修改</el-button>
                  <el-button type="danger"
                             size="small"
                             @click="deleteExperiments">删除</el-button>
                </div>
                <el-table :data="experiments"
                          ref="experimentsRef"
                          border>
                  <el-table-column type="selection"
                                   width="55">
                  </el-table-column>
                  <el-table-column label="课题名称"
                                   width="150">
                    <template slot-scope="scope">
                      <el-input v-if="isAdmin"
                                v-model="scope.row.exName" />
                      <span v-else>{{scope.row.exName}}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="课题描述"
                                   width="550">
                    <template slot-scope="scope">
                      <el-input v-if="isAdmin"
                                v-model="scope.row.exDescription" />
                      <span v-else>{{scope.row.exDescription}}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="课题类别"
                                   width="150">
                    <template slot-scope="scope">
                      <el-select v-if="isAdmin"
                                 v-model="scope.row.tyId"
                                 placeholder="请选择">
                        <el-option v-for="item in exTypes"
                                   :key="item.id"
                                   :label="item.typeName"
                                   :value="item.id">
                        </el-option>
                      </el-select>
                      <span v-else>{{scope.row.typeName}}</span>
                    </template>
                  </el-table-column>
                  <el-table-column v-if="!isAdmin"
                                   label="评价"
                                   prop="rate"
                                   width="180">
                    <template slot-scope="scope">
                      <el-rate v-model="scope.row.rate"
                               disabled
                               show-score
                               text-color="#ff9900"
                               :score-template="String(scope.row.rate)">
                      </el-rate>
                    </template>
                  </el-table-column>
                  <el-table-column prop="createdTime"
                                   label="开设时间">
                  </el-table-column>
                </el-table>
                <el-pagination layout="prev, pager, next"
                               :total="exPage.total"
                               :page-size="exPage.size"
                               @current-change="clickExPage">
                </el-pagination>
              </el-col>
            </el-row>
          </template>
        </el-tab-pane>
        <el-tab-pane name="查看小组"
                     :label="isAdmin ? '小组管理' : '查看小组'"
                     style="width:1400px">
          <template>
            <el-form inline>
              <el-form-item label="小组名称"
                            label-width="80px">
                <el-input v-model="searchGroupFrom.name" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary"
                           @click="searchGroup">搜索</el-button>
              </el-form-item>
              <el-form-item>
                <el-button v-if="!isAdmin"
                           type="success"
                           @click="showCreateGroupDialog">创建小组</el-button>
              </el-form-item>
            </el-form>
            <el-row>
              <el-col>
                <div v-if="isAdmin"
                     style="text-align:left;margin-bottom:10px">
                  <el-button type="warning"
                             size="small"
                             @click="saveGroups">保存修改</el-button>
                </div>
                <el-table :data="groups"
                          ref="groupsRef"
                          border>
                  <el-table-column type="selection"
                                   width="55">
                  </el-table-column>
                  <el-table-column label="小组名称"
                                   width="200">
                    <template slot-scope="scope">
                      <el-input v-if="isAdmin"
                                v-model="scope.row.name" />
                      <span v-else>{{scope.row.name}}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="小组宣言"
                                   width="550">
                    <template slot-scope="scope">
                      <el-input v-if="isAdmin"
                                v-model="scope.row.declaration" />
                      <span v-else>{{scope.row.declaration}}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="研究课题名称"
                                   width="150">
                    <template slot-scope="scope">
                      <el-select v-if="isAdmin"
                                 v-model="scope.row.exId">
                        <el-option v-for="item in experimentList"
                                   :key="item.id"
                                   :label="item.exName"
                                   :value="item.id">
                        </el-option>
                      </el-select>
                      <span v-else>{{scope.row.exName}}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="当前人数"
                                   width="80">
                    <template slot-scope="scope">
                      <span>{{scope.row.userIds ? scope.row.userIds.split(',').length : 0 }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="size"
                                   label="人数上限"
                                   width="80">
                  </el-table-column>
                  <el-table-column prop="createdTime"
                                   label="创建时间"
                                   width="200">
                  </el-table-column>
                  <el-table-column v-if="!isAdmin"
                                   label="操作">
                    <template slot-scope="scope">
                      <el-button v-if="scope.row.createdBy != user.id && scope.row.userIds.indexOf(user.id) == -1"
                                 type="text"
                                 @click="joinGroup(scope.row)">加入</el-button>
                      <span v-else-if="scope.row.userIds.indexOf(user.id) != -1">{{ '已加入' }}</span>
                      <span v-else-if="scope.row.status == 1">{{ groupStatus[scope.row.status] }}</span>
                    </template>
                  </el-table-column>
                </el-table>
                <el-pagination layout="prev, pager, next"
                               :total="groupPage.total"
                               :page-size="groupPage.size"
                               @current-change="clickGroupPage">
                </el-pagination>
              </el-col>
            </el-row>
          </template>
        </el-tab-pane>
        <el-tab-pane name="预约实验室"
                     :label="isAdmin ? '实验室管理' : '预约实验室'"
                     style="width:1400px">
          <template>
            <el-form :model="searchLaboratorieyFrom"
                     inline>
              <el-form-item label="实验室名称"
                            label-width="100px">
                <el-input v-model="searchLaboratorieyFrom.labName" />
              </el-form-item>
              <el-form-item label="实验室地址"
                            label-width="100px">
                <el-input v-model="searchLaboratorieyFrom.labAddress" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary"
                           @click="searchLaboratoriey">搜索</el-button>
              </el-form-item>
            </el-form>
            <div v-if="isAdmin"
                 style="text-align:left;margin-bottom:10px">
              <el-button type="success"
                         size="small"
                         @click="laboratories.push({})">新增</el-button>
              <el-button type="warning"
                         size="small"
                         @click="saveLaboratories">保存修改</el-button>
              <el-button type="danger"
                         size="small"
                         @click="deleteLaboratories">删除</el-button>
            </div>
            <el-table :data="laboratories"
                      border
                      ref="labRef">
              <el-table-column type="selection"
                               width="55">
              </el-table-column>
              <el-table-column prop="labName"
                               label="实验室名称"
                               width="200">
                <template slot-scope="scope">
                  <el-input v-if="isAdmin"
                            v-model="scope.row.labName" />
                  <span v-else>{{scope.row.labName}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="labDesc"
                               label="实验室简介"
                               width="600">
                <template slot-scope="scope">
                  <el-input v-if="isAdmin"
                            v-model="scope.row.labDesc" />
                  <span v-else>{{scope.row.labDesc}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="labCode"
                               label="地址"
                               width="220">
                <template slot-scope="scope">
                  <el-input v-if="isAdmin"
                            v-model="scope.row.labAddress" />
                  <span v-else>{{scope.row.labAddress}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="rate"
                               label="实验室评价"
                               width="180">
                <template slot-scope="scope">
                  <el-rate v-model="scope.row.rate"
                           disabled
                           show-score
                           text-color="#ff9900"
                           :score-template="String(scope.row.rate)">
                  </el-rate>
                </template>
              </el-table-column>
              <el-table-column v-if="!isAdmin"
                               label="操作">
                <template slot-scope="scope">
                  <el-button type="text"
                             @click="openReserveDialog(scope.row)">预约</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination layout="prev, pager, next"
                           :total="labPage.total"
                           :page-size="labPage.size"
                           @current-change="clickLabPage">
            </el-pagination>
          </template>
        </el-tab-pane>
        <el-tab-pane name="用户管理"
                     label="用户管理"
                     v-if="isAdmin"
                     style="width:1400px">
          <el-form inline>
            <el-form-item label="用户账号"
                          label-width="80px">
              <el-input v-model="searchUserFrom.userName" />
            </el-form-item>
            <el-form-item label="用户昵称"
                          label-width="80px">
              <el-input v-model="searchUserFrom.nickName" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary"
                         @click="searchUser">搜索</el-button>
            </el-form-item>
          </el-form>
          <div style="text-align:left;margin-bottom:10px">
            <el-button type="warning"
                       size="small"
                       @click="saveUsers">保存修改</el-button>
            <el-button type="danger"
                       size="small"
                       @click="deleteUsers">删除</el-button>
          </div>
          <el-table :data="users"
                    ref="usersRef">
            <el-table-column type="selection"
                             width="55">
            </el-table-column>
            <el-table-column label="用户账号"
                             width="200"
                             prop="userName">
            </el-table-column>
            <el-table-column label="用户昵称"
                             width="200">
              <template slot-scope="scope">
                <el-input v-model="scope.row.nickName" />
              </template>
            </el-table-column>
            <el-table-column label="手机号"
                             width="200">
              <template slot-scope="scope">
                <el-input v-model="scope.row.phone" />
              </template>
            </el-table-column>
            <el-table-column label="系别"
                             width="200"
                             prop="tieName">
            </el-table-column>
            <el-table-column label="班级"
                             prop="className">
            </el-table-column>
            <el-table-column label="所属小组"
                             prop="groupName">
            </el-table-column>
            <el-table-column label="用户类型">
              <template slot-scope="scope">
                <span>{{ scope.row.userType == 2 ? '管理员' : '普通用户' }}</span>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination layout="prev, pager, next"
                         :total="userPage.total"
                         :page-size="userPage.size"
                         @current-change="clickUserPage">
          </el-pagination>
        </el-tab-pane>
      </el-tabs>
      <el-steps v-if="!isAdmin"
                :active="activeStep"
                finish-status="success"
                direction="vertical"
                style="margin-left:20px;margin-top:20px;width:200px;height: 400px">
        <el-step title="浏览所有课题"></el-step>
        <el-step title="加入或创建小组"></el-step>
        <el-step title="预约空闲实验室"></el-step>
      </el-steps>
      <el-dialog title="预约实验室"
                 :visible.sync="isShowReserveDialog"
                 width="30%">
        <el-form label-width="110px"
                 :model="reserveForm"
                 :rules="reserveFormRules"
                 ref="reserveFormRef">
          <el-form-item prop="labName"
                        label="实验室名称">
            <el-input style="width:305.75px;"
                      disabled
                      v-model="reserveForm.labName" />
          </el-form-item>
          <el-form-item prop="labAddress"
                        label="地址">
            <el-input style="width:305.75px;"
                      disabled
                      v-model="reserveForm.labAddress" />
          </el-form-item>
          <el-form-item prop="serveStartTime"
                        label="开始时间">
            <el-date-picker format="yyyy-MM-dd HH:mm:ss"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            style="width:305.75px;"
                            v-model="reserveForm.serveStartTime"
                            type="datetime"
                            placeholder="开始时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item prop="serveEndTime"
                        label="结束时间">
            <el-date-picker format="yyyy-MM-dd HH:mm:ss"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            style="width:305.75px;"
                            v-model="reserveForm.serveEndTime"
                            :picker-options="endPickerOptions"
                            type="datetime"
                            placeholder="结束时间">
            </el-date-picker>
          </el-form-item>
        </el-form>
        <span slot="footer"
              class="dialog-footer">
          <el-button type="primary"
                     @click="reserveLab">确 定</el-button>
          <el-button @click="isShowReserveDialog = false">取 消</el-button>
        </span>
      </el-dialog>
      <el-dialog title="创建小组"
                 :visible.sync="isShowCreateGroupDialog"
                 width="25%">
        <el-form label-width="110px"
                 :model="createGroupFrom"
                 ref="createGroupFrom"
                 :rules="createGroupRules">
          <el-form-item prop="name"
                        label="小组名称">
            <el-input v-model="createGroupFrom.name" />
          </el-form-item>
          <el-form-item prop="declaration"
                        label="小组宣言">
            <el-input type="textarea"
                      v-model="createGroupFrom.declaration" />
          </el-form-item>
          <el-form-item prop="size"
                        label="人数上限">
            <el-input-number style="width:331px"
                             :min="2"
                             :max="50"
                             v-model="createGroupFrom.size" />
          </el-form-item>
          <el-form-item prop="exId"
                        label="研究课题名称">
            <el-select style="width:331px"
                       v-model="createGroupFrom.exId">
              <el-option v-for="item in experimentList"
                         :key="item.id"
                         :label="item.exName"
                         :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer"
              class="dialog-footer">
          <el-button type="primary"
                     @click="createGroup">确 定</el-button>
          <el-button @click="isShowCreateGroupDialog = false">取 消</el-button>
        </span>
      </el-dialog>

      <el-dialog title="我的个人信息"
                 :visible.sync="isShowMyUserInfo"
                 width="25%">
        <el-form label-width="80px"
                 :model="myUserForm"
                 :rules="myUserRules"
                 ref="myUserForm">
          <el-form-item label="用户名"
                        prop="userName">
            <el-input disabled
                      v-model="myUserForm.userName" />
          </el-form-item>
          <el-form-item label="昵称"
                        prop="nickName">
            <el-input v-model="myUserForm.nickName" />
          </el-form-item>
          <el-form-item label="手机号"
                        prop="phone">
            <el-input v-model="myUserForm.phone" />
          </el-form-item>
          <el-form-item label="系别"
                        prop="tieId">
            <el-select style="width:356px"
                       v-model="myUserForm.tieId">
              <el-option v-for="item in ties"
                         :key="item.id"
                         :label="item.tieName"
                         :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="班级"
                        prop="classId">
            <el-select style="width:356px"
                       v-model="myUserForm.classId">
              <el-option v-for="item in myClasses"
                         :key="item.id"
                         :label="item.className"
                         :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="所属小组"
                        prop="groupName">
            <el-input disabled
                      style="width:250px"
                      v-model="myUserForm.groupName" />
            <el-button :disabled="myUserForm.groupId == 0"
                       style="margin-left:5px"
                       type="danger"
                       @click="quitGroup">退出小组</el-button>
          </el-form-item>
        </el-form>
        <span slot="footer"
              class="dialog-footer">
          <el-button type="primary"
                     @click="saveMyUserInfo">提 交</el-button>
          <el-button @click="isShowMyUserInfo = false">取 消</el-button>
        </span>
      </el-dialog>

      <el-dialog title="修改密码"
                 :visible.sync="isShowChangePwd"
                 width="25%">
        <el-form label-width="80px"
                 :model="changePwdForm"
                 :rules="changePwdRules"
                 ref="changePwdForm">
          <el-form-item label="旧密码"
                        prop="oldPassword">
            <el-input type="password"
                      v-model="changePwdForm.oldPassword" />
          </el-form-item>
          <el-form-item label="新密码"
                        prop="password">
            <el-input type="password"
                      v-model="changePwdForm.password" />
          </el-form-item>
          <el-form-item label="确认密码"
                        prop="password2">
            <el-input type="password"
                      v-model="changePwdForm.password2" />
          </el-form-item>
        </el-form>
        <span slot="footer"
              class="dialog-footer">
          <el-button type="primary"
                     @click="changePassword">修 改</el-button>
          <el-button @click="isShowChangePwd = false">取 消</el-button>
        </span>
      </el-dialog>

      <el-dialog title="我的待办"
                 :visible.sync="isShowApprovalDialog"
                 width="25%">
        <el-table :data="toDoList"
                  border>
          <el-table-column v-if="!isAdmin"
                           prop="groupName"
                           label="小组名称">
          </el-table-column>
          <el-table-column v-if="!isAdmin"
                           prop="createByName"
                           label="申请人">
          </el-table-column>
          <el-table-column v-if="isAdmin"
                           prop="labName"
                           label="实验室名称">
          </el-table-column>
          <el-table-column v-if="isAdmin"
                           prop="createByGroupName"
                           label="申请小组">
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-link type="primary"
                       @click="approval('2',scope.row.id)">同意</el-link>&nbsp;
              <el-link type="danger"
                       @click="approval('1',scope.row.id)">驳回</el-link>
            </template>
          </el-table-column>
        </el-table>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="isShowApprovalDialog = false">关 闭</el-button>
        </span>
      </el-dialog>
    </el-container>
  </div>
</template>

<script>
export default {
  data () {
    let vm = this
    return {
      userPage: {
        current: 1,
        size: 7,
        total: 0
      },
      exPage: {
        current: 1,
        size: 7,
        total: 0
      },
      groupPage: {
        current: 1,
        size: 7,
        total: 0
      },
      labPage: {
        current: 1,
        size: 7,
        total: 0
      },
      isShowMyUserInfo: false,
      users: [],
      searchUserFrom: {},
      axios: null,
      activeStep: 0,
      isAdmin: false,
      user: {},
      exTypes: [],
      activeName: '查看课题',
      createGroupFrom: {
      },
      isShowReserveDialog: false,
      isShowCreateGroupDialog: false,
      timePickerOptions: {
        start: '08:30',
        step: '00:30',
        end: '18:30'
      },
      createGroupRules: {
        name: [
          { required: true, message: '小组名不能为空', trigger: 'blur' },
          { min: 4, max: 16, message: '长度在 4 到 16 个字符', trigger: 'blur' }
        ],
        declaration: [
          { required: true, message: '小组描述不能为空', trigger: 'blur' },
          { min: 10, max: 50, message: '长度在 10 到 50 个字符', trigger: 'blur' }
        ],
        exId: [
          { required: true, message: '研究课题不能为空', trigger: 'change' }
        ],
        size: [
          { required: true, message: '人数上限不能为空', trigger: 'blur' }
        ]
      },
      searchGroupFrom: {},
      endPickerOptions: {
        disabledDate: (time) => {
          return time.getTime() < new Date(vm.reserveForm.serveStartTime).getTime()
        }
      },
      page: {
        current: 1,
        size: 8
      },
      experiments: [
      ],
      searchExperimentForm: {
      },
      laboratories: [
      ],
      groups: [],
      selectedLaboratory: {
      },
      reserveForm: {

      },
      experimentList: [],
      isShowApprovalDialog: false,
      groupStatus: {
        0: '审批中',
        1: '未通过',
        2: '已通过'
      },
      ties: [],
      toDoList: [],
      messageList: [],
      classes: [],
      myClasses: [],
      timer: null,
      webSocket: null,
      reserveFormRules: {
        serveStartTime: [
          { required: true, message: '开始时间不能为空', trigger: 'blur' }
        ],
        serveEndTime: [
          { required: true, message: '结束时间不能为空', trigger: 'blur' }
        ]
      },
      myUserForm: {
      },
      myUserRules: {
        nickName: [
          { required: true, message: '昵称不能为空', trigger: 'blur' },
          { min: 2, max: 16, message: '长度在 2 到 16 个字符', trigger: 'blur' }
        ],
        tieId: [
          { required: true, message: '系别不能为空', trigger: 'blur' }
        ],
        grade: [
          { required: true, message: '年级不能为空', trigger: 'blur' }
        ],
        classId: [
          { required: true, message: '班级不能为空', trigger: 'blur' }
        ],
      },
      searchLaboratorieyFrom: {
        current: 1,
        size: 8
      },
      isShowChangePwd: false,
      changePwdForm: {},
      changePwdRules: {
        oldPassword: [
          { required: true, message: '旧密码不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '新密码不能为空', trigger: 'blur' }
        ],
        password2: [
          { required: true, message: '确认密码不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    myUserForm: {
      handler: function (val) {
        if (val) {
          let { tieId } = val
          if (tieId) {
            this.$axios.get('sysClass', { params: { tid: tieId } }).then(res => {
              let data = res.data
              this.myClasses = data
            })
          }
        }
      },
      deep: true
    }
  },
  computed: {
    hasToDo () {
      let toDoList = this.toDoList
      if (toDoList && toDoList.length > 0) {
        return true
      } else {
        return false
      }
    }
  },
  created () {
    let isLogout = this.$session.get('isLogout')
    if (isLogout) {
      this.$router.push({ path: '/' })
    }
    this.axios = this.$axios.create()
    this.axios.defaults.headers.common['access_token'] = this.$session.get('access_token')
    this.getCurrentUser()
    this.findExTypeList()
    this.findMyToDoList()
    this.searchExperiment()

    this.$axios.get('sysTie').then(res => {
      let data = res.data
      this.ties = data
    })

    Date.prototype.format = function (fmt) {
      var o = {
        "M+": this.getMonth() + 1,                 //月份 
        "d+": this.getDate(),                    //日 
        "h+": this.getHours(),                   //小时 
        "m+": this.getMinutes(),                 //分 
        "s+": this.getSeconds(),                 //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds()             //毫秒 
      };
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
      }
      for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
      }
      return fmt;
    }
  },
  beforeDestroy () {
    this.$once('hook:beforeDestroy', () => {
      if (this.webSocket) {
        this.webSocket.close()
      }
      clearInterval(this.timer)
    })
  },
  methods: {
    getCurrentUser () {
      this.axios.get('user').then(res => {
        let user = res.data
        if (user) {
          if (user.userType == '2') {
            this.isAdmin = true
          }
          this.user = user
          this.myUserForm = user
          this.$session.set('user', user)
          this.initWebSocket()
        }
      })
    },
    logout () {
      this.$session.set('user', {})
      this.$session.set('isLogout', true)
      // 跳转登录界面
      this.$router.push({ path: '/' })
    },
    selectedTab (obj) {
      switch (obj.name) {
        case '用户管理':
          this.searchUser()
          break
        case '查看课题':
          this.searchExperiment()
          this.activeStep = 0
          break
        case '查看小组':
          this.activeStep = 1
          this.searchGroup()
          break
        case '预约实验室':
          this.searchLaboratoriey()
          this.activeStep = 2
          break
      }
    },
    findExTypeList () {
      this.axios.get('exType').then(res => {
        this.exTypes = res.data
      })
    },
    openReserveDialog (laboratory) {
      this.axios.get('group/getMySysGroup').then(res => {
        let data = res.data
        if (!data) {
          this.$message({
            type: 'warning',
            message: '请先加入或创建小组!'
          })
          return
        } else {
          this.reserveForm.labName = laboratory.labName
          this.reserveForm.labAddress = laboratory.labAddress
          this.reserveForm.applyId = laboratory.id
          this.isShowReserveDialog = true
        }
      })
    },
    searchExperiment () {
      this.searchExperimentForm.current = this.exPage.current
      this.searchExperimentForm.size = this.exPage.size
      this.searchExperimentForm.delFlag = '0'
      this.axios.get('experiment', { params: this.searchExperimentForm }).then(res => {
        let records = res.data.records
        if (records) {
          for (let item of records) {
            try {
              item.createdTime = new Date(new Date(item.createdTime).getTime()).format("yyyy-MM-dd hh:mm:ss")
            } catch (error) {
              console.log(error)
            }
            item.rate = Number(String(Math.random() + 4).substring(0, 3))
          }
          this.experiments = records
          this.exPage.total = res.data.total
        }
      })
    },
    saveExperiments () {
      let data = this.experiments
      this.axios.put('experiment', data).then(res => {
        if (res.status === 200) {
          this.$message({
            type: 'success',
            message: '保存成功!'
          })
          this.searchExperiment()
        } else {
          this.$message({
            type: 'warning',
            message: '保存失败!'
          })
        }
      })
    },
    deleteExperiments () {
      let data = this.$refs.experimentsRef.selection
      let deleteDatas = []
      for (let item of data) {
        if (item.id) {
          deleteDatas.push(item.id)
        } else {
          this.experiments.splice(this.experiments.indexOf(item), 1)
        }
      }
      if (deleteDatas.length === 0) {
        return
      }
      this.axios.delete('experiment', { data: deleteDatas }).then(res => {
        if (res.status === 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.searchExperiment()
        } else {
          this.$message({
            type: 'warning',
            message: '删除失败!'
          })
        }
      })
    },
    searchGroup () {
      this.searchGroupFrom.current = this.groupPage.current
      this.searchGroupFrom.size = this.groupPage.size
      this.axios.get('group', { params: this.searchGroupFrom }).then(res => {
        let records = res.data.records
        if (records) {
          for (let item of records) {
            try {
              item.createdTime = new Date(new Date(item.createdTime).getTime()).format("yyyy-MM-dd hh:mm:ss")
            } catch (error) {
              console.log(error)
            }
          }
          this.groups = records
          this.groupPage.total = res.data.total
        }
      })
    },
    createGroup () {
      this.$refs['createGroupFrom'].validate((valid) => {
        if (valid) {
          let array = []
          array.push(this.createGroupFrom)
          this.axios.post('group', array).then(res => {
            if (res.data.code != 0) {
              this.$message({
                type: 'success',
                message: '创建成功!'
              })
              this.createGroupFrom = {}
              this.isShowCreateGroupDialog = false
              this.searchGroup()
            } else {
              this.$message({
                type: 'warning',
                message: '您已拥有小组!'
              })
            }
          })
        } else {
          return valid
        }
      })
    },
    saveGroups () {
      this.axios.post('group', this.groups).then(res => {
        if (res.status === 200) {
          this.$message({
            type: 'success',
            message: '保存成功!'
          })
          this.searchGroup()
        } else {
          this.$message({
            type: 'warning',
            message: '保存失败!'
          })
        }
      })
    },
    deleteGroups () {
      let data = this.$refs.groupsRef.selection
      let deleteDatas = []
      for (let item of data) {
        if (item.id) {
          deleteDatas.push(item.id)
        } else {
          this.groups.splice(this.groups.indexOf(item), 1)
        }
      }
      if (deleteDatas.length === 0) {
        return
      }
      this.axios.delete('group', { data: deleteDatas }).then(res => {
        if (res.status === 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.searchExperiment()
        } else {
          this.$message({
            type: 'warning',
            message: '删除失败!'
          })
        }
      })
    },
    saveLaboratories () {
      this.axios.post('lab', this.laboratories).then(res => {
        if (res.status === 200) {
          this.$message({
            type: 'success',
            message: '保存成功!'
          })
          this.searchGroup()
        } else {
          this.$message({
            type: 'warning',
            message: '保存失败!'
          })
        }
      })
    },
    deleteLaboratories () {
      let data = this.$refs.labRef.selection
      let deleteDatas = []
      for (let item of data) {
        if (item.id) {
          deleteDatas.push(item.id)
        } else {
          this.laboratories.splice(this.laboratories.indexOf(item), 1)
        }
      }
      if (deleteDatas.length === 0) {
        return
      }
      this.axios.delete('lab', { data: deleteDatas }).then(res => {
        if (res.status === 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.searchLaboratoriey()
        } else {
          this.$message({
            type: 'warning',
            message: '删除失败!'
          })
        }
      })
    },
    showCreateGroupDialog () {
      this.isShowCreateGroupDialog = true
      let searchExperimentForm = {
        current: 1,
        size: 999
      }
      this.findExperimentList(searchExperimentForm)
    },
    findExperimentList (searchExperimentForm) {
      this.axios.get('experiment', { params: searchExperimentForm }).then(res => {
        let records = res.data.records
        if (records) {
          for (let item of records) {
            try {
              item.createdTime = new Date(new Date(item.createdTime).getTime()).format("yyyy-MM-dd hh:mm:ss")
            } catch (error) {
              console.log(error)
            }
            item.rate = Number(String(Math.random() + 4).substring(0, 3))
          }
          this.experimentList = records
        }
      })
    },
    joinGroup (group) {
      this.axios.post(`approval/joinGroup?groupId=${group.id}`).then(res => {
        let msgType = ''
        if (res.data.code == 3) {
          this.searchGroup()
          msgType = 'success'
        } else {
          msgType = 'warning'
        }
        this.$message({
          type: msgType,
          message: res.data.message
        })
      })
    },
    findMyToDoList () {
      let data = {
        current: 1,
        size: 99
      }
      this.axios.get('approval', { params: data }).then(res => {
        let records = res.data.records
        if (records) {
          this.toDoList = records
        }
      })
    },
    showApprovalDialog () {
      this.isShowApprovalDialog = true
    },
    approval (state, id) {
      if (!this.isAdmin) {
        this.axios.post(`approval/updateStatus?state=${state}&id=${id}`).then(res => {
          let data = res.data
          if (data.code == 0) {
            this.$message({
              type: 'success',
              message: data.message
            })
          } else {
            this.$message({
              type: 'warning',
              message: data.message
            })
          }
          this.findMyToDoList()
        })
      } else {
        this.axios.post(`approval/approvalReseve?state=${state}&id=${id}`).then(res => {
          let data = res.data
          if (data.code == 0) {
            this.$message({
              type: 'success',
              message: data.message
            })
          } else {
            this.$message({
              type: 'warning',
              message: data.message
            })
          }
          this.findMyToDoList()
        })
      }

    },
    findMessageList () {
      this.axios.get('message').then(res => {
        let data = res.data
        let ids = []
        if (data) {
          for (let item of data) {
            ids.push(item.id)
            let timer = setTimeout(() => {
              this.$notify({
                title: '消息提醒',
                message: item.content,
                duration: 0,
                offset: 100
              })
            }, 5000)
            clearTimeout(timer)
          }
        }
        if (ids.length > 0) {
          this.findMyToDoList()
          this.axios.post('message', ids)
        }
      })
    },
    searchLaboratoriey () {
      this.searchLaboratorieyFrom.current = this.labPage.current
      this.searchLaboratorieyFrom.size = this.labPage.size
      this.axios.get('lab', { params: this.searchLaboratorieyFrom }).then(res => {
        let records = res.data.records
        if (records) {
          for (let item of records) {
            try {
              item.createdTime = new Date(new Date(item.createdTime).getTime()).format("yyyy-MM-dd hh:mm:ss")
            } catch (error) {
              console.log(error)
            }
            item.rate = Number(String(Math.random() + 4).substring(0, 3))
          }
          this.laboratories = records
          this.labPage.total = res.data.total
        }
      })
    },
    reserveLab () {
      this.$refs.reserveFormRef.validate(res => {
        if (res) {
          let approval = {
            applyId: this.reserveForm.applyId,
            serveStartTime: this.reserveForm.serveStartTime,
            serveEndTime: this.reserveForm.serveEndTime,
            labName: this.reserveForm.labName
          }
          this.axios.post('approval/reserveLab', approval).then(res => {
            let data = res.data
            if (data.code == 0) {
              this.$message({
                type: 'success',
                message: '预约成功!'
              })
              this.isShowReserveDialog = false
            } else if (data.code == 1) {
              this.$message({
                type: 'warning',
                message: '该实验室在该时间段内已被预约!'
              })
            } else if (data.code == 3) {
              this.$message({
                type: 'warning',
                message: '您当前已申请过实验室预约，请等待审批!'
              })
            }
          })
        } else {
          return false
        }
      })

    },
    initWebSocket () {
      let vm = this
      this.webSocket = new WebSocket(`ws://localhost:8081/laboratory/message/${this.user.id}`)
      this.webSocket.onmessage = (data) => {
        console.log(data)
      }
      this.webSocket.onpen = () => {
        vm.webSocket.send(this.user.id)
      }
      this.webSocket.onmessage = (res) => {
        let dataStr = res.data
        let ids = []
        if (dataStr == 'null') {
          return
        }
        let messageArray = JSON.parse(dataStr)
        for (let item of messageArray) {
          ids.push(item.id)
          if (item.content && item.content.indexOf('同意')) {
            this.axios.get('user').then(res => {
              let user = res.data
              if (user) {
                this.myUserForm = user
              }
            })
          }
          setTimeout(() => {
            vm.$notify({
              title: '消息提醒',
              message: item.content,
              duration: 0,
              offset: 100
            })
          }, 5000)
        }
        if (ids.length > 0) {
          this.findMyToDoList()
          this.axios.post('message', ids)
        }
      }
      this.timer = setInterval(() => {
        this.webSocket.send(this.user.id)
      }, 5000)
    },
    showMyUserInfo () {
      this.isShowMyUserInfo = true
    },
    searchUser () {
      this.searchUserFrom.current = this.userPage.current
      this.searchUserFrom.size = this.userPage.size
      this.axios.post('user/list', this.searchUserFrom).then(res => {
        let records = res.data.records
        this.users = records
        this.userPage.total = res.data.total
      })
    },
    deleteUsers () {
      let data = this.$refs.usersRef.selection
      let deleteDatas = []
      for (let item of data) {
        if (item.id) {
          deleteDatas.push(item.id)
        } else {
          this.users.splice(this.users.indexOf(item), 1)
        }
      }
      if (deleteDatas.length === 0) {
        return
      }
      this.axios.delete('user', { data: deleteDatas }).then(res => {
        if (res.status === 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.searchUser()
        } else {
          this.$message({
            type: 'warning',
            message: '删除失败!'
          })
        }
      })
    },
    saveUsers () {
      this.axios.put('user', this.users).then(res => {
        if (res.status === 200) {
          this.$message({
            type: 'success',
            message: '保存成功!'
          })
          this.searchUser()
        } else {
          this.$message({
            type: 'warning',
            message: '保存失败!'
          })
        }
      })
    },
    clickUserPage (val) {
      this.userPage.current = val
      this.searchUser()
    },
    clickExPage (val) {
      this.exPage.current = val
      this.searchExperiment()
    },
    clickGroupPage (val) {
      this.groupPage.current = val
      this.searchGroup()
    },
    clickLabPage (val) {
      this.labPage.current = val
      this.searchLaboratoriey()
    },
    findClassByTie (rowData) {
      this.$axios.get('sysClass', { params: { tid: rowData.tieId } }).then(res => {
        let data = res.data
        this.classes = data
      })
    },
    changePassword () {
      let { password, password2 } = this.changePwdForm
      if (password !== password2) {
        this.$message({
          type: 'warning',
          message: '两次输入密码不一致!'
        })
        return
      }
      this.$refs.changePwdForm.validate(flag => {
        if (flag) {
          this.axios.post('user/change/password', this.changePwdForm).then(res => {
            let code = res.data.code
            if (code == 0) {
              this.$message({
                type: 'success',
                message: '修改成功!'
              })
              this.isShowChangePwd = false
              this.changePwdForm = {}
            } else {
              this.$message({
                type: 'warning',
                message: '旧密码不正确!'
              })
            }
          })
        }
      })
    },
    saveMyUserInfo () {
      let users = []
      users.push(this.myUserForm)
      this.axios.put('user', users).then(res => {
        if (res.status === 200) {
          this.$message({
            type: 'success',
            message: '保存成功!'
          })
          this.isShowMyUserInfo = false
        } else {
          this.$message({
            type: 'warning',
            message: '保存失败!'
          })
        }
      })
    },
    quitGroup () {
      let users = []
      let tempForm = {
        id: this.myUserForm.id,
        groupId: 0
      }
      users.push(tempForm)
      this.axios.put('user', users).then(res => {
        if (res.status === 200) {
          this.$message({
            type: 'success',
            message: '退出成功!'
          })
          this.myUserForm.groupId = ''
          this.myUserForm.groupName = ''
        } else {
          this.$message({
            type: 'warning',
            message: '退出失败!'
          })
        }
      })
    }
  }
}
</script>